package com.freeter.common.provincecity;

import com.freeter.common.mpextend.parser.ParseWrapper;
import com.freeter.modules.cityrecord.entity.CitiesEntity;
import com.freeter.modules.cityrecord.entity.ProvincesEntity;
import com.freeter.modules.cityrecord.entity.model.CitiesModel;
import com.freeter.modules.cityrecord.entity.model.ProvincesModel;
import com.freeter.modules.cityrecord.service.CitiesService;
import com.freeter.modules.cityrecord.service.ProvincesService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * User: jinjueYang
 * Date: 2019/4/3
 * Time: 14:08
 * Description:
 */
@Component
public class ProvinceCityCache implements InitializingBean {

    private static final Map<String, ProvincesEntity> PROVINCE_MAP = new ConcurrentHashMap();
    private static final Map<String, CitiesEntity> CITY_MAP = new ConcurrentHashMap();
    private static List<ProvincesEntity> PROVINCE_LIST = null;
    //省id对应市区关系表
    private static Map<String, List<CitiesEntity>> PROVINCE_CITIES_MAP = null;

    @Autowired
    private ProvincesService provincesService;
    @Autowired
    private CitiesService citiesService;

    public static ProvincesEntity getProvince(String provinceId) {
        return PROVINCE_MAP.get(provinceId);
    }

    public static CitiesEntity getCity(String cityId) {
        return CITY_MAP.get(cityId);
    }

    public static List<ProvincesEntity> getAllProvinces() {
        return PROVINCE_LIST;
    }

    public static List<CitiesEntity> getCitiesByProvinceId(String provinceId) {
        return PROVINCE_CITIES_MAP.get(provinceId);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        PROVINCE_LIST = provincesService.selectList(ParseWrapper.parseWrapper(new ProvincesModel()));
        PROVINCE_LIST.forEach(vo -> PROVINCE_MAP.put(vo.getProvinceid(), vo));
        List<CitiesEntity> citiesList = citiesService.selectList(ParseWrapper.parseWrapper(new CitiesModel()));
        citiesList.forEach(vo -> CITY_MAP.put(vo.getCityid(), vo));
        PROVINCE_CITIES_MAP = citiesList.stream().collect(Collectors.groupingBy(CitiesEntity::getProvinceid));
    }
}
